#include <iostream>
#include "UdpClient.h"
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "comm.h"
#include <pthread.h>
#include <signal.h>
int sockfd = -1;
struct sockaddr_in serve;

void ClientQuit(int signo)
{
    (void)signo;
    const std::string quit = "QUIT";
    int n = ::sendto(sockfd, quit.c_str(), quit.size(), 0, CONV(&serve), sizeof(serve));
    exit(0);
}
void *Recver(void *args)
{
    while (true)
    {
        (void)args;
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&temp), &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl; // 代码没问题，重定向也没问题，管道读写同时打开，才会继续向后运行
            // fprintf(stderr, "%s\n", buffer);
            // fflush(stderr);
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "usage" << argv[0] << "serverip serveport" << std::endl;
        Die(1);
    }
    signal(2, ClientQuit);
    std::string serveip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        Die(2);
    }

    memset(&serve, 0, sizeof(serve));
    serve.sin_family = AF_INET;
    serve.sin_port = ::htons(serverport);
    serve.sin_addr.s_addr = ::inet_addr(serveip.c_str());
    pthread_t tid;
    const std::string online = " ... 来了哈!";
    pthread_create(&tid, nullptr, Recver, nullptr);
    int n = ::sendto(sockfd, online.c_str(), online.size(), 0, CONV(&serve), sizeof(serve));
    while (1)
    {
        std::cout << "please Enter#";
        std::string message;
        std::getline(std::cin, message);

        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&serve), sizeof(serve));
        (void)n;
    }

    return 0;
}